package com.team.book.service.impl;

import com.team.book.common.constant.ResponseStatus;
import com.team.book.common.domain.Page;
import com.team.book.common.exception.UncheckedException;
import com.team.book.common.util.UserUtil;
import com.team.book.domain.BorrowedRecord;
import com.team.book.domain.User;
import com.team.book.mapper.UserMapper;
import com.team.book.service.UserService;
import com.team.book.web.dto.BorrowedRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by haolw on 4/22/17.
 *
 * @version 0.0.1
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserDetailsService,UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.userMapper.findUserByUsername(username);
        return user;
    }

    @Override
    public Page<User> query(Page<User> page, User user) {
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        long count = userMapper.count(map);
        map.put("limit",page.getPageSize());
        map.put("offset",page.getOffset());
        page.setTotalCount(count);
        List<User> list = userMapper.query(map);
        page.setResult(list);
        return page;
    }


    @Override
    public int save(User user) throws UncheckedException {
        User u = this.userMapper.findUserByUsername(user.getUsername());
        if(u==null){
            return userMapper.insert(user);
        }else{
            throw new UncheckedException(ResponseStatus.USER_EXIST.getMessage());
        }
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public int updatePwd(User user) throws UncheckedException {
        User u = this.getById(user.getId());
        if(u==null){
            throw new UncheckedException(ResponseStatus.NOT_FOUND.getMessage());
        }
        if(u.getId()!= UserUtil.getCurUser().getId()){
            throw new UncheckedException(ResponseStatus.NOT_AUTH.getMessage());
        }
        return userMapper.updatePwd(user);
    }

    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }
}
